package com.kgc.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.kgc.api.goods.OrderApi;
import com.kgc.bean.OrderInfo;
import com.kgc.bean.OrderItem;
import com.kgc.bean.User;
import com.kgc.config.WechatAuthConfig;
import com.kgc.config.WxpayConfig;
import com.kgc.constant.WxpayConstant;
import com.kgc.service.UserService;
import com.kgc.service.WeChatPayService;
import com.kgc.util.HttpClient4Util;
import com.kgc.util.RedisUtils;
import com.kgc.util.WXPayXmlUtil;
import com.kgc.util.WxpayUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;

/**
 * @Classname WeChatPayServiceImpl
 * @Description TODO
 * @Date 2021/6/23 16:45
 * @Created by 17402
 */

@Service
@Slf4j
public class WeChatPayServiceImpl implements WeChatPayService {
    @Autowired
    private WxpayConfig wxpayConfig;
    @Autowired
    private UserService userService;
    @Reference(timeout = 30000)
    private OrderApi orderApi;
    @Autowired
    private RedisUtils redisUtils;


    @Override
    public String createWxorderParam2XmlStr(String totalFee, String buyDetail, String spbillCreateIp, String token) throws Exception {
        //创建一个有序集合，要求自然排序
        Map<String, String> paramsMap = new TreeMap<>();
        // 应用id
        paramsMap.put("appid", wxpayConfig.getAppId());
        //商户id
        paramsMap.put("mch_id", wxpayConfig.getMchId());
        //设备号
        paramsMap.put("device_info", "WEB");
        // 随机字符串
        paramsMap.put("nonce_str", WxpayUtil.generateNonceStrByWx(32));
        // 商品描述
        paramsMap.put("body", StringUtils.isEmpty(buyDetail) ? "购买vip" : buyDetail);
        // 商户订单号
        paramsMap.put("out_trade_no", WxpayUtil.generateOutTrade());
        // 金额
        paramsMap.put("total_fee", totalFee);
        //终端ip
        paramsMap.put("spbill_create_ip", spbillCreateIp);
        //支付回调地址
        paramsMap.put("notify_url", wxpayConfig.getNotifyUrl());
        // 交易类型
        paramsMap.put("trade_type", "NATIVE");
        // 商品id trade_type=NATIVE时，此参数必传
        paramsMap.put("product_id", "vip");
        if(null!=token&&!"".equals(token)){
            paramsMap.put("attach",token);
        }
        //签名，使用上面所有参数，sign不是签名参数，签名类型默认MD5
        paramsMap.put("sign",WxpayUtil.generateSignature(paramsMap,wxpayConfig.getMchKey(), WxpayConstant.WXPAY_SIGN_TYPE_MD5));
        //将封装好的参数map集合转化为微信接口需要的xml 格式数据
        return WxpayUtil.mapToXml(paramsMap);
    }

    @Override
    public Map<String, String> send2WechatPayOrder(String wxPayParamsXmlStr) throws Exception {
        //官方要求请求方法是post,返回的内容是xml数据
        String response4PostByString = HttpClient4Util.getResponse4PostByString(wxpayConfig.getOrderUrl(), wxPayParamsXmlStr, WxpayConstant.WXPAY_FIELD_ECODING_UTF8);

        //解析返回的xml
        return WxpayUtil.xmlToMap(response4PostByString);
    }

    @Override
    public String resolveWechatPayNotify(String wxPayNotify,OrderItem orderItem) throws Exception { if (null != wxPayNotify && !"".equals(wxPayNotify)) {
        // xml 2 map
        Map<String, String> stringStringMap = WxpayUtil.xmlToMap(wxPayNotify);

        // 只处理成功返回
        if (WxpayConstant.WXPAY_RETURN_SUCCESS.equals(stringStringMap.get(WxpayConstant.WXPAY_RETURN_CODE))) {
            log.info("------3 微信支付结果回调成功：{}", stringStringMap);

            // 签名校验，验证签名的有效性
            if (WxpayUtil.isSignatureValid(stringStringMap, wxpayConfig.getMchKey())) {

                log.info("------4 验签成功,自己订单状态修改");
                log.info("------------4.1 attach: {}",stringStringMap.get("atatch"));
                if (userService.renewingMember(stringStringMap.get("attach"))) {
                    User user= JSON.parseObject(redisUtils.get(stringStringMap.get("attach")).toString(),User.class);
                    OrderInfo orderInfo=OrderInfo.builder()
                            .orderId(orderItem.getOrderId())
                            .orderPayment(1)
                            .orderStatus(2)
                            .orderCreateTime(new Date())
                            .orderPaymentTime(new Date())
                            .userId(user.getUserId())
                            .orderPaymentType(2)
                            .lastPaymentPrice(1)
                            .build();
                    log.info("----------------orderIfo：{}",orderInfo.toString());
                    if(orderApi.saveOrderInfo(orderInfo)){
                        log.info("----------订单状态修改成功-------------");
                    };
                    log.info("会员开通或续费成功！");


                } else {
                    log.info("会员开通或续费失败！");
                }
                return WxpayConstant.WXPAY_RETURN_SUCCESS;

            }
            return WxpayConstant.WXPAY_RETURN_SUCCESS;
        }
    }
        return WxpayConstant.WXPAY_RESPONSE_FILE;
    }
}
